import base from './base';
import * as API_REQ from '../apis/req';
import * as _ from './public/common';
import * as FieldUtil from './public/fieldUtil';
import * as DetailUtil from './public/detailUtil';
import * as GlobalUtil from './public/globalUtil';
import WfForm_Public from './public/interface';
import * as AI from './public/analyzeData';
import { closeUnLock } from './lockUtil';
import { bindOnMessage } from './public/invoiceUtil'
import { getAntd,getEcCom,getLabel } from './convert';
import { toJS } from 'mobx';
import * as type from "../constants/type";
import wfWaterMark from './public/wfWaterMark';
import * as continuationProcessUtil from './continuationProcessUtil';

//绑定外层放大缩小事件
export const bindResizeEvent = ()=>{
    jQuery(window).bind('resize', () => {
        let height = jQuery(".wea-new-top-req-content").height() ? jQuery(".wea-new-top-req-content").height() : 600;
        const{ tabKey } = base.globalStore;
        if(tabKey === "pic"){
            setFormPic( height );
        }else if(tabKey === "odoc"){
            jQuery(".wf-req-odoc").height(height - 20);
            jQuery(".req-workflow-odoc").height(height - 20);
        }
    });
}

//根据event获取keycode(兼容火狐)
export const convertKeyCode = (e) => {
    e = e.nativeEvent ? e.nativeEvent : e;
	e = e ? e : window.event;
	var keyCode = e.nativeEvent ? e.nativeEvent.keyCode : e.which;
    return keyCode;
}

//获取浏览器版本
export const getBrowserVersion = () => {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
    if (isChrome)
        return "Chrome";

    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if(isEdge)
        return "Edge";
    if(isIE11)
        return "IE11";
    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7)
            return "IE7";
        else if (fIEVersion == 8)
            return "IE8";
        else if (fIEVersion == 9)
            return "IE9";
        else if (fIEVersion == 10)
            return "IE10";
        else if (fIEVersion == 11)
            return "IE11";
        else
            return "IE";
    }
    var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
    var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
    var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器  
    if (isOpera)
        return "Opera";
    if (isFF)
        return "FF";
    if (isSafari)
        return "Safari";
    return "unident";
}

//页面标题
export const getPageTitle = () => {
    let pageTitle = "";
    const {globalStore, layoutStore} = base;
    const { commonParam, urlParams } = globalStore;
    if(urlParams.isPreView === "1")
        return getLabel(31568,'模板预览');
    const {mainData} = layoutStore;
    const {iscreate, workflowname} = commonParam;
    if (!_.isEmpty(commonParam) && parseInt(iscreate) === 1) {
        pageTitle = `${getLabel(83443,'创建')} - ${workflowname}`;
    } else if (mainData.has("field-1")) {
        pageTitle = mainData.get("field-1").value;
    } else {
        pageTitle = `${getLabel(553,'处理')} - ${workflowname}`;
    }
    return pageTitle;
}

//刷新表单
let isRefreshAction = false;
export const reloadRequestPage = (params, appendUserStr=true) => {
    const {globalStore} = base;
    globalStore.setCloseNeedPrompt(false);
    if(appendUserStr === true){     //扩展用户信息
        const { f_weaver_belongto_userid,f_weaver_belongto_usertype,wfTestStr } = globalStore.commonParam;
        params = {...{f_weaver_belongto_userid,f_weaver_belongto_usertype,wfTestStr}, ...params};
    }
    //添加连续处理信息
    const { isOpenContinuationProcess } = globalStore.urlParams;
    params = {isOpenContinuationProcess, ...params};
    if(params.requestid == globalStore.commonParam.requestid) {//刷新表单，将连续处理的信息传入url中
        params.isRefresh = '1';
        appendContinuationParams(params);
    }
    isRefreshAction = true;
    gotoPage("/workflow/request/ViewRequestForwardSPA.jsp", params);
}

//跳转指定链接
export const gotoPage = (url, params = {}) => {
    try {
        ReactDOM.unmountComponentAtNode(document.getElementById("container"));
    } catch (e) {
        if (window.console) console.log(e);
    }
    window.location.href = `${url}?${buildUrlStr(params)}`;
}

//拼接url链接
export const buildUrlStr = (params = {}) => {
    let str = "";
    _.forIn(params, (value, key) => {
        str += `&${key}=${value}`;
    });
    if (str !== "")
        str = str.substring(1);
    return str;
}

//关闭页面,控制是否需要提示
export const closeRequestPage = (needPrompt = true, params={}) => {
    const { requestid=-1 } = params;
    const {globalStore} = base;
    const {urlParams = {}, continuationProcessInfo = {}} = globalStore;
    globalStore.setCloseNeedPrompt(needPrompt);
    reloadListPage();
    closeUnLock();  //流程编辑锁定关闭解锁
    GlobalUtil.verifyCustomRegisterEvent(WfForm_Public.OPER_CLOSE, ()=>{

        if(urlParams.isOpenContinuationProcess == '1') {
            try{
                //连续处理调用时切换下一条流程
                continuationProcessUtil.switchRequest('next', true);
                return;
            }catch(e){}
        }

        try{
            window.top.close();
        }catch(e){
            window.close();
        }
        if(!window.opener){
            requestid > -1 ? reloadRequestPage({requestid}) : window.location.reload();
        }
    }, params);
}

window.onbeforeunload = (e) => {
    e = e || window.event;
    const {closeNeedPrompt, commonParam} = base.globalStore;
    const {existChangeFormData} = base.layoutStore;
    if(!isRefreshAction)
        closeUnLock();  //非刷新情况下解锁
    isRefreshAction = false;
    if (closeNeedPrompt && commonParam.requestType !== 0 && existChangeFormData) {
        const tipMsg = getLabel(18877,"流程还没保存，如果离开，将会丢失数据，真的要离开吗？");
        if (e)
            e.returnValue = tipMsg;
        return tipMsg;
    }
}

//打印耗时
export const printDuration = (params, needRecord=false) =>{
    try{
        if(window.console){
            console.log(`请求id: ${params.requestid}`);
            console.log(`js加载耗时: ${window.JS_LOAD_DURATION || 0}毫秒`);
            console.log(`中转耗时: ${window.Route_DURATION || 0}毫秒`);
            console.log(`异步js耗时: ${window.ASYNC_DURATION || 0}毫秒`);
            console.log(`服务端耗时: ${window.SERVER_DURATION || 0}毫秒`);
            console.log(`接口耗时: ${window.API_DURATION || 0}毫秒`);
            console.log(`渲染耗时: ${window.DISPATCH_DURATION || 0}毫秒`);
            console.log(`总耗时: ${window.REQ_LOAD_DURATION / 1000 || 0}秒`);
        }
        const { globalStore } = base;
        const { browserVersion,commonParam,commonApiParam } = globalStore;
        if(needRecord === true && !commonParam.belongTest){    //耗时信息入库
            const params = {
                url: window.location.href,
                moduleType: 14,
                clientType: browserVersion,
                interfaceTc: window.API_DURATION,
                serviceTc: window.SERVER_DURATION,
                renderTc: window.DISPATCH_DURATION,
                staticTc: window.JS_LOAD_DURATION,
                allTc: window.REQ_LOAD_DURATION,
                param: JSON.stringify(commonApiParam)
            };
            API_REQ.writeDurationTimeInfo(params);
        }
    }catch(e){}
}
window.printDuration = printDuration;

//刷新列表
export const reloadListPage = (params) => {
    let reloadParams = {};
    try {
        //刷新待办列表
        const { baseParam } = base.globalStore;
        reloadParams = {...baseParam, ...params};
        window.opener._table.reLoad(reloadParams);
    } catch (e) {}
    try {
        //刷新门户列表
        jQuery(window.opener.document).find('#btnWfCenterReload').click();
    } catch (e) {}
    try {
      //刷新流程中心待办列表元素
      window.opener.backlogRefresh();
    } catch (e) {}
    try {
      //刷新流程中心关注列表元素
      window.opener.attentionRefresh();
    } catch (e) {}
    try {
      //刷新流程中心新反馈列表元素
      window.opener.refreshResponseList();
    } catch (e) {}
    try {
        //从公文待办列表打开流程 刷新待办页面列表
        window.opener && window.opener.isOdocOpenWF && window.opener.getOdocWFList()
    } catch (e) { }
}

//空值转换
export const convertNull = (value, bool=true) =>{
    if(value === null || typeof value === "undefined")
        return "";
    else
        return bool ? value.toString() : value;
}

//加载代码块及custompage
export const loadScript = () => {
    const promiseList = GlobalUtil.generateScriptPromiseList();
    const { isSourceLayout, commonParam={} } = base.globalStore;
    const { useInvoiceCloud } = commonParam;
    const { layoutSourceInfo } = base.layoutStore;
    Promise.all(promiseList).then((result)=>{
        const successFn = () =>{
            jQuery("#customScriptDiv").html("");
            if(isSourceLayout)  //源码模板代码块不发请求
                result.push(layoutSourceInfo.script);
            result.forEach((item,index) =>{
                try{
                    const tempstr = GlobalUtil.manageScriptContent(item);
                    jQuery("#customScriptDiv").append(`<div class="_custom_script_${index}">${tempstr}</div>`);
                    if(!isSourceLayout && index === result.length-1)
                        AI.setScriptContent(tempstr);
                }catch(e){}
            });
            GlobalUtil.loadCustomFiles("js");
            GlobalUtil.loadFormulaResource();
            window.__Load_Script_Complete__ = true;     //标识代码块加载完成
            if(!judgePrintLogList())    //打印不包含意见弹打印预览，包含意见的情况再意见组件加载完弹出
                printPreViewPage();
            //公文流程执行页面加载事件
            const { odocInfo } = base.layoutStore;
            if(odocInfo && odocInfo.docFlag === true)
                window.oDocUtil.loadOdocConfig();
        }
        base.globalStore.pushJSCompleteEvent(successFn);
    });
    if (useInvoiceCloud == true) {
        bindOnMessage();
    }
}

//打印判断是否打印签字意见列表
export const judgePrintLogList = () =>{
    const { globalStore,layoutStore } = base;
    const { commonParam, rightMenu, isSourceLayout } = globalStore;
    const { isprint,isHideArea,printLogListFlag } = commonParam;
    const { forward } = rightMenu;
    const { cellInfo } = layoutStore;
    let printLogList = false;
    if(parseInt(isprint) == 1 && isHideArea != "1"){
        if(printLogListFlag === 0){ //始终不打印
        }else if(printLogListFlag === 2){   //始终打印
            printLogList = true;
        }else {     //默认为节点意见放入模板中不打印
            if(isSourceLayout){
                const nodeMarkContent = cellInfo.nodeMarkContent || {};
                printLogList = _.isEmpty(nodeMarkContent);
            }else{
                printLogList = !cellInfo.existCurrentWfNodeMark;
            }
        }
    }
    return printLogList;
}

//弹出打印预览界面
export const printPreViewPage = () =>{
    const { browserVersion,urlParams,commonParam } = base.globalStore;
    if(parseInt(commonParam.isprint) !== 1)
        return;
    if(urlParams.isBatchPrint === "true"){
        const begintime = new Date().getTime();
        const batchPrintTimer = window.setInterval(() =>{
            //批量打印给iframe赋值高度
            const requestid = commonParam.requestid;
            const printObj = jQuery(".wf-req-print");
            const iframeObj = jQuery("iframe#request_"+requestid, window.parent.document);
            iframeObj.css("height", printObj.height() + 10);
            //至多循环等待3s
            if(new Date().getTime() - begintime > 3000)
                window.clearInterval(batchPrintTimer);
        }, 200);
        return;
    }
    if(urlParams.isPreView === "true")
        return;
    const printFn = () =>{
        const timeout = isNaN(parseInt(WfForm.printTimeout||"")) ? 500 : parseInt(WfForm.printTimeout);
        window.setTimeout(function(){
            if(browserVersion.indexOf("IE") > -1){
                try{
                    //通过修改电脑注册表，控制IE下打印设置，默认勾选允许收缩到纸张大小
                    var hkey_root = "HKEY_CURRENT_USER" ;
                    var hkey_path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
                    var hkey_key = "";
                    var RegWsh = new ActiveXObject("WScript.Shell");
                    hkey_key = "Print_Background";
                    RegWsh.RegWrite(hkey_root+hkey_path+hkey_key, "yes");
                    hkey_key = "Shrink_To_Fit";
                    RegWsh.RegWrite(hkey_root+hkey_path+hkey_key, "yes");
                }catch(e){
                    if(window.console)
                        console.log("请设置IE下允许ActiveX插件运行,"+e);
                }
                try {
                    document.all.WebBrowser.ExecWB(7,1);    //IE下弹预览
                } catch(e9) {
                    window.print();
                }
            }else{
                window.print();
            }
        }, timeout);
    }
    const begTime = new Date().getTime();
    const printTimer = window.setInterval(() =>{
        if(window.__Load_Script_Complete__ === true || new Date().getTime() - begTime > 10000){   //至多等待10s弹预览
            GlobalUtil.verifyCustomRegisterEvent(WfForm_Public.OPER_PRINTPREVIEW, printFn);
            window.clearInterval(printTimer);
        }
    }, 200);
}

window.printPreViewPage = printPreViewPage;

/**
 * 控制提示组件
 * @param {*} mark  提示字段则为field110_3、提示明细表则是detail_2
 * @param {*} promptType   1提示必填字段，2提示行规则赋值字段不可编辑，3提示未新增明细
 */
export const showPrompt = (mark, promptType) =>{
    if(!mark)
        return;
    const { layoutStore } = base;
    const { fieldAttrMap,cellInfo } = layoutStore;
    let fieldid = "";
    let fieldAttr = null;
    let lableText = "";
    if(promptType === 1 || promptType === 2){
        fieldid = mark.indexOf("_") > -1 ? mark.substring(5,mark.indexOf("_")) : mark.substring(5);
        fieldAttr = fieldAttrMap.get(fieldid);
        lableText = fieldAttr && fieldAttr.fieldlabel || "";
    }else if(promptType === 3){
        lableText = `${getLabel(19325,'明细表')}${mark.substring(7)}`;
    }

    let changeInfo = {};
    let changeTabMark = "";
    changeInfo["promptBox"] = {mark, lableText, promptType:promptType, visible:true};
    if(promptType === 1){
        if(fieldAttr && fieldAttr.isonlyshow === 1)
            changeInfo.promptBox.isFieldOnlyShow = true;
        else
            changeInfo["promptRequiredField"] = mark;
        //如果字段是标签页字段，需默认选择标签页
        const belSymbol = _.get(cellInfo, ["fieldCellInfo", fieldid, "symbol"]) || "";
        if(belSymbol.indexOf("mc_") > -1 || belSymbol.indexOf("detail_") > -1)   //多字段、明细字段再取上一层
            changeTabMark = _.get(cellInfo, ["subPanelInfo", belSymbol, "symbol"]) || "";
        else
            changeTabMark = belSymbol;
    }else if(promptType === 3){
        changeTabMark = _.get(cellInfo, ["subPanelInfo", mark, "symbol"]) || "";
    }
    //提示区域在标签页中，需要切换标签页选中项
    if(changeTabMark.indexOf("tab_") > -1){
        const tabPanelInfo = _.get(cellInfo, ["subPanelInfo", changeTabMark]) || {};
        if(!_.isEmpty(tabPanelInfo))
            changeInfo[`tabarea_${tabPanelInfo.rowid}_${tabPanelInfo.colid}_showid`] = changeTabMark;
    }
    layoutStore.batchControlVariableMap(changeInfo);
    const { Modal } = getAntd();
    const { dialogVisible, controlDialogVisible } = base.globalStore;
    let _dialogVisible = dialogVisible.has(type.FREE_WORKFLOW_SIMPLE) && dialogVisible.get(type.FREE_WORKFLOW_SIMPLE) ;
    _dialogVisible && Modal.warning({
        title: getLabel(28535, `信息提示`),
        content: getLabel(513127,"表单有必填项未填写"),
        okText: getLabel(83446,'确定'),
        onOk() {
            controlDialogVisible(type.FREE_WORKFLOW_SIMPLE, false);
        },
    });
    //延时清除状态
    window.setTimeout(function(){
        let recoverData = {};
        recoverData["promptBox"] = {visible:false};
        if(promptType === 1)
            recoverData["promptRequiredField"] = "";
        layoutStore.batchControlVariableMap(recoverData);
    },1500);
}

//流转设定弹窗存在时弹出必填应该弹出提示


//删除明细行
export const delRow = (detailMark) =>{
    const detailObj = DetailUtil.getDetailObj(detailMark);
    if(detailObj === null)
        return;
    const rowArr = DetailUtil.getDetailCheckedRowArr(detailObj);
    if(rowArr.length === 0)
        return;
    const { Modal } = getAntd();
    Modal.confirm({
        title:getLabel(131329,'信息确认'),
        content: getLabel(15097,'确定要删除吗？'),
        okText:getLabel(826,'确定'),
        cancelText:getLabel(201,'取消'),
        onOk() {
            DetailUtil.delAssignRow(detailMark, rowArr);
        },
        onCancel() {},
    });
}

//调用客户自定义回掉函数
export const doDefinitionCallBackFun = (fieldid, rowIndex, ids, datas, fieldAttr) => {
    if(typeof(wfbrowvaluechange) === "function"){
        wfbrowvaluechange(null, fieldid, rowIndex);
    }
    const { detailtype,isDetail } = fieldAttr;
    if(typeof(__browVal4CustomCheck) === "function"){
        const { workflowid,requestid } = base.globalStore.commonParam;
    	const fieldMark  = isDetail ? `field${fieldid}_${rowIndex}` : `field${fieldid}`;
     	__browVal4CustomCheck(fieldid, workflowid, requestid, detailtype, ids, datas, fieldMark);
    }
    //报销费用类型
    if(detailtype === 22){
    	try{
            const { WeaTools } = getEcCom();
    		WeaTools.callApi('/api/fna/budgetfeeTypeBrowser/updateBudgetfeeTypeUsed', 'GET', {subjectId:ids});
    	}catch(e){
            if(window.console) console.log(e)
        }
    }

    //报销费用类型
    if(detailtype === 300){
        const { WeaTools } = getEcCom();
        const { workflowid,requestid } = base.globalStore.commonParam;
    	try{
    		WeaTools.callApi('/api/fnaMulDimensions/fnaWfDimTypeBrowserUser/updateWfDimTypeUsed','POST',
                {
                    memberId:ids,
                    fieldId:fieldid,
                    workflowId:workflowid
                }
            );
    	}catch(e){
            if(window.console)
            console.log(e)
        }

    }
}

//获取流程干预默认值
export const getIntervenorDefaultV = (data = {}) => {
    let updateinfo = {Intervenorid : '', IntervenoridType : ''};
    let { items = []} = data;
    let nodeOperators =  data.replacedatas || [];
    if (items.length > 0) {
        items.map((item) => {
            const {labelcol, fieldcol, label, conditionType, domkey = [], browserConditionParam = {}, options = []} = item;
            if (conditionType == 'SELECT') {
                options.map((o) => {
                    if (o.selected) updateinfo[domkey[0]] = o.key;
                })
            } else if (conditionType == 'BROWSER') {
                const {replaceDatas = []} = browserConditionParam;
                let ids = [];
                replaceDatas.map((o) => {
                    ids.push(o.id);
                })
                updateinfo[domkey[0]] = ids.join(',');
                if('Intervenorid' == domkey[0]) nodeOperators = replaceDatas;
            }
        });
    }
    if (nodeOperators && nodeOperators.length > 0) {
        let ids = [];
        let operatortypes = [];
        nodeOperators.map(o => {
            const {id, IntervenoridType = ''} = o;
            ids.push(id);
            operatortypes.push(IntervenoridType);
        });
        updateinfo.Intervenorid = ids.join(',');
        updateinfo.IntervenoridType = operatortypes.join(',');
    }
    return updateinfo;
}

//流程导入
export const requestImport =(imprequestid) =>{
    const {commonParam,setLoading} = base.globalStore;
    setLoading(true);
    const {workflowid,formid,isbill,nodeid,nodetype,isagent,beagenter} = commonParam;
    let requestname = '';
    let requestlevel = '';
    const fieldObj = FieldUtil.getFieldValObj(-1,-1);
    const fieldObjReqLevel = FieldUtil.getFieldValObj(-2,-1);
    if(fieldObj) {
        const {valueObj = {}} = fieldObj;
        const {value = ''} = valueObj;
        requestname = value;
    }
    if(fieldObjReqLevel) {
        const {valueObj = {}} = fieldObjReqLevel;
        const {value = ''} = valueObj;
        requestlevel = value;
    }
    const importParams = {
        src:"import",
        imprequestid:imprequestid,
        workflowid:workflowid,
        formid:formid,
        isbill:isbill,
        nodeid:nodeid,
        "nodetype":nodetype,
        isagent:isagent,
        beagenter:beagenter,
        requestname:requestname,
        requestlevel:requestlevel
    };
    API_REQ.requestImport(importParams).then(data=>{
        reloadRequestPage({requestid:data.requestid});
    });
}

export const setFormPic = (height)=>{

    const picUrl = getIframeUrl();
    (jQuery(".req-workflow-map").attr("src") != picUrl) && jQuery(".req-workflow-map").attr("src", picUrl);//给ifream添加src
    jQuery(".req-workflow-map").height(height - 5);
}


export const getIframeUrl = (params = {})=>{
  const {baseParam, rightMenu,variableMap,commonParam,urlParams} = base.globalStore;
  let picParams  = {...toJS(urlParams),...toJS(baseParam)};
  const {requestid} = baseParam;
  let picHtml = 'readOnly-index.html';
  if(variableMap.get(type.FREEFLOW_SETTING) || requestid > 0) {
      const {hasFreeNode = false} = commonParam;
      const {isFree = '0',isAllowNodeFreeFlow = '0'} = rightMenu;
      picParams['isFree'] = isFree;
      picParams['isAllowNodeFreeFlow'] = isAllowNodeFreeFlow;
      picParams['isReadOnlyModel'] = true;
      picParams['isFlowModel'] = '0';
      picParams['hasFreeNode'] = hasFreeNode ? '1':'0';
  }
  picParams.authSignatureStr = commonParam.authSignatureStr;
  picParams.authStr = commonParam.authStr;
  picParams.wfTestStr = commonParam.wfTestStr;

  picParams = {...picParams, ...params};
  const picUrl = `/workflow/workflowDesign/${picHtml}?${buildUrlStr(picParams)}&showE9Pic=1&isFromWfForm=true&_freekey=${variableMap.get('FREE_T_KEY')}`;
  return picUrl
}

//切换tab
export const switchFormTab = (key = '', jumpTab = true) => {
    if(!base.globalStore.JSComplete)
        return;
	if(key=='odoc'&&(jQuery(".req-workflow-odoc").length>0||jQuery(".wf-req-form-odoc-iframe")>0)&&WfForm.getOdocConfig().docParam.isTextInFormCanEdit&&WfForm.getOdocConfig().docParam.isTextInForm){
		return;
	}		
    if(WfForm.getOdocConfig()  != null && WfForm.getOdocConfig().docParam != null && WfForm.getOdocConfig().docParam.saveDocRemind === true && getWebOfficeIsModify() === true && key != "odoc" && base.globalStore.tabKey === "odoc"){
        //开启离开正文提醒，且公文未保存，离开正文页面，进行提醒
        const { Modal } = getAntd();
        showOrHideWeboffice(0);
        Modal.confirm({
            title:getLabel(131329,'信息确认'),
            content: getLabel(19006,'文档还没保存，确定要离开吗？'),
            okText:getLabel(826,'确定'),
            cancelText:getLabel(201,'取消'),
            onOk() {
                switchFormTabFunc(key,jumpTab);
                showOrHideWeboffice(1);
            },
            onCancel() {
                showOrHideWeboffice(1);
            },
        });
    }else{
        switchFormTabFunc(key,jumpTab);
    }
}


//切换tab
export const switchFormTabFunc = (key = '', jumpTab = true) => {
    const oldTabKey = base.globalStore.tabKey;
    if (key.indexOf('custom_dialog_') === -1 && jumpTab) {
        base.globalStore.setTabKey(key);
    }
    const contentDiv = jQuery(".wea-new-top-req-content");
    contentDiv.css("overflow-y", (key === "form" || key === "pic" || key === "resource") ? "hidden" : "auto");
    let height = 0;
    if(key === 'pic') {
      height = contentDiv.height()-50 ? contentDiv.height()-50: 600;  //处理流程图没有滚动条的问题
    } else {
      height = contentDiv.height() ? contentDiv.height() : 600;
    }

    //控制正文页签
    jQuery(".wf-req-odoc").show();
    if(jQuery(".wf-req-odoc").length> 0){
        if (key === "odoc"){
            jQuery(".wf-req-odoc").css('height','100%');
			showOrHideWeboffice(1);
            jQuery(".wf-req-odoc").css('marginTop','10px');
            jQuery(".wf-req-odoc").css('marginBottom', '10px');
            jQuery(".req-workflow-odoc").css('width','100%');
            //解决正文切换回表单，正文+无法点击的问题
            try {
                oDocUtil.uploadPDFCanClick=true;
            }catch (e) {
            }

        }else{
			if (key === "form" && WfForm.getOdocConfig().opentextdefaultnode&&jQuery(".wf-req-form-odoc-iframe").length>0) {
				if(WfForm.getOdocConfig().docParam.mcount==undefined){
					WfForm.getOdocConfig().docParam.mcount = 0
				}
				if(WfForm.getOdocConfig().docParam.mcount==0){
					WfForm.getOdocConfig().docParam.mcount=1;
					const formsrc = jQuery(".wf-req-form-odoc-iframe").attr("src");
					jQuery(".wf-req-form-odoc-iframe").attr("src",formsrc);
				}
			}
            jQuery(".wf-req-odoc").height(1);
            let marginTop = parseInt(jQuery(".wf-req-odoc").css('fontSize').replace('px',''),10);
            marginTop = (marginTop > 0) ? marginTop = (marginTop + 1) * -1 : -13;
            jQuery(".wf-req-odoc").css('marginTop',marginTop + 'px');
            jQuery(".wf-req-odoc").css('marginBottom','0px');
            jQuery(".req-workflow-odoc").height(1);
			showOrHideWeboffice(0);
        }
    }
    if (key === "form") {
        DetailUtil.fixedDetailHead();
        window.formLoglistStore && window.formLoglistStore.loadMarkInfo();
    } else if (key === "pic") {
        setFormPic(height);
        if(!base.smartGuessWfStore.baseReqParams.requestid) {
          base.smartGuessWfStore.init(base.globalStore.commonParam);
        }
    } else if (key === "odoc") {
        try {
			if((jQuery(".req-workflow-odoc").length>0||jQuery(".wf-req-form-odoc-iframe")>0)&&WfForm.getOdocConfig().docParam.isTextInFormCanEdit&&WfForm.getOdocConfig().docParam.isTextInForm){
				WfForm.switchTab("form");
				return;
			}			
            oDocUtil.setDocParam();
        	jQuery(".req-workflow-odoc").height(height - 20); 
        } catch (e) {
        }
    } else if (key.indexOf('custom_') > -1) {
        try {
            let fun = WfForm.customTabFunObj[key];
            if (typeof fun === 'function') {
                fun();
            }
        } catch (e) {
            if (window.console) console.log(e);
        }
    }
    //处理流程图操作者信息面板隐藏的问题
    let obj = document.getElementById('wfFrontOperator-container');
    if(obj) {
      if(key !== 'pic') {
        obj.style.visibility = 'hidden';
      }
    }
    //后执行注册事件
    window.WfForm.triggerAction(window.WfForm.ACTION_SWITCHTAB, [key, oldTabKey]);
}

//流程提交后显示流程图
export const showChart = (requestid) => {
    const {globalStore} = base;
    const {submitParam = {},rightMenu,commonParam,urlParams} = globalStore;
    const {workflowid, isbill, formid, isfromtab, f_weaver_belongto_userid, f_weaver_belongto_usertype} = submitParam;
    const urlParam = {
        ...toJS(urlParams),
        requestid,
        workflowid,
        isbill,
        formid,
        isfromtab,
        f_weaver_belongto_userid,
        f_weaver_belongto_usertype,
        showE9Pic: "1",
        isFromAutodirect:"1",
        isFromWfForm:true,
        authSignatureStr:commonParam.authSignatureStr,
        authStr:commonParam.authStr,
        wfTestStr:commonParam.wfTestStr
    };
    const {isFree = '0',isAllowNodeFreeFlow = '0'} = rightMenu;
    urlParam['isFree'] = isFree;
    urlParam['isAllowNodeFreeFlow'] = isAllowNodeFreeFlow;

    //跳转流程图，拼接连续处理参数
    appendContinuationParams(urlParam);

    gotoPage("/workflow/request/WorkflowDirectionNew.jsp", urlParam);
}

//拼接连续处理参数
export const appendContinuationParams = (urlParam = {}) => {
    const {globalStore} = base;
    const { continuationProcessInfo } = globalStore;
    if(continuationProcessInfo.loaded) {
        urlParam.isOpenContinuationProcess = '1';
        urlParam.currentIndex = continuationProcessInfo.currentIndex;
        urlParam.counts = continuationProcessInfo.counts;
    }
    return urlParam;
}

//右键按钮是否显示判断
export const isShowRightBtn = (btnInfo = {}) =>{
    const { globalStore } = base;
    const { tabKey } = globalStore;
    const { type, menuName, menuIcon,isTest } = btnInfo;
    let isShow = true;
    //导出
    if(type == 'BTN_EXCEL' && tabKey !== 'form') {
        isShow = false;
    }
    return isShow;
}

export const bindTagTypeShowEvent = () =>{
    jQuery("body").on("click", function(e) {
        if((jQuery(e.target).parents(".icon-coms02-Label").length > 0) || jQuery(e.target).hasClass("icon-coms02-Label"))
        return;
        if(jQuery(e.target).parents(".ant-popover-content").length < 1){//icon-coms02-Label
            base.followSelectStore.followTypeSelectShow = false;
        }
    })
}


//滚动dom元素到页面可视区域
export const scrollDom = (dom=".wf-req-freeWorkflowSimple",borderHeightLight=false,msg) =>{
    const { message } = getAntd();
    let  remarktop = parseInt(jQuery(dom).offset().top);
    let scrolltop = 0;
    //判断dom元素区域是否在可视区域
    const isVisual = remarktop > 0 && (remarktop - jQuery('.wea-new-top-req').height() + 200 <  jQuery('.wf-req-form-scroll').height());
    if(!isVisual) {
        if(remarktop - jQuery('.wea-new-top-req').height() + 200 > jQuery('.wf-req-form-scroll').height()){
            scrolltop = remarktop + jQuery('.wf-req-form-scroll').scrollTop() - 385;
        }
        if(remarktop <  (jQuery('.wea-new-top-req').height())){
            if(remarktop < 0) remarktop = remarktop * -1;
            scrolltop = jQuery('.wf-req-form-scroll').scrollTop() - remarktop - jQuery('.wea-new-top-req').height()-350;// -100;
        }
        jQuery('.wf-req-form-scroll').animate({ scrollTop: scrolltop + "px" }, 0);
        
    }
    if(msg){
        message.warning(msg);
    }
    if(borderHeightLight){
        jQuery(dom).css("border","1px solid #2DB7F5")
    }
}

//获取流程导入需要的参数
export const getWfImportParams = () =>{
    const { rightMenu, commonParam } = base.globalStore;
    const rightMenus = rightMenu && rightMenu.rightMenus || [];
    let params={}
    rightMenus  instanceof Array && rightMenus.map(m => {
        const {type, menuName, menuIcon, menuFun, isTop, isLockShow, isTest} = m;
        if (menuFun.indexOf("doImportWorkflow") > -1){
            const userId = commonParam.f_weaver_belongto_userid || "";
            const { workflowid, formid, isbill, belongTest } = commonParam;
            params={
                workflowid,
                formid,
                isbill,
                belongTest,
                userId,
                menuName
            }
        }
    })
    return params;
}

/**
 * 加载水印
 */
export const loadWaterMark = () => {
    const {commonParam = {},urlParams = {}} = base.globalStore;
    const {waterMarkInfo} = commonParam;
    const {browser = '',version = '0'} = window.ua;
    if(browser === "IE" && parseInt(version, 10) < 11) return;
    if(waterMarkInfo) {
        const {contentType = 0,content = "",width = 0,height = 0,transparency = 0,rotationAngle = 0} = waterMarkInfo;
        const waterMarkOptions = {
            fontStyle: "font-size:18px;color:#000;",
            rotate: 360-rotationAngle,
            alpha: transparency/100,
            width,
            height
        };

        if(contentType == 1) {
            let tempContent  = content;
            const regx = /<span key=\"(.*?)\"><\/span>/g;
            while (regx.exec(content) != null) {
                const fieldMark  = RegExp.$1;
                const valShowName =  GlobalUtil.getWaterMarkFieldShowName(fieldMark);
                tempContent = tempContent.replace(`<span key="${fieldMark}"></span>`,`<span>${valShowName}</span>`);
            }
            waterMarkOptions.text = wfWaterMark.formatContent({text:tempContent});
        }
        if(contentType == 2) waterMarkOptions.src = content;

        const {isBatchPrint = 'false',isPreView='false'} = urlParams;
        let doc = null;
        if(isBatchPrint == 'true'||isPreView == 'true') {
            doc = window.document;
            let index  = 0;
            let timer = setInterval(()=>{
                if(index < 20) {
                    wfWaterMark(waterMarkOptions,doc);
                    index++;
                } else {
                    clearInterval(timer);
                }
            },200);
        } else {
            wfWaterMark(waterMarkOptions,doc);
        }
    }
}

